package com.smarthome.BoxAndroidNew;

import org.json.JSONException;
import org.json.JSONObject;

import com.smarthome.BoxAndroidNew.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	EditText txtIp,txtPort;
	Button btnLogin;
	private String Tag1 = "SigninActivity";
	private String Tag2 = "Loginactivity";
	ProgressDialog progress;
	private ProgressDialog pDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		 txtIp=(EditText)findViewById(R.id.txtIp);
		 txtIp.setText("Son");
		 txtPort=(EditText)findViewById(R.id.txtPort);
		 txtPort.setTag("123");
		 btnLogin=(Button)findViewById(R.id.btbLogin);
		
		
		btnLogin.setOnClickListener(new OnClickListener() {
			
		
			@SuppressLint("NewApi")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try{
					LocalData.strIP = txtIp.getText().toString();
					LocalData.strport = Integer.parseInt(txtPort.getText().toString());
					Loader aslogin = new Loader();
					 aslogin.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
					}
					catch(Exception e)
					{
						Log.e(Tag2,"cant start asycn"+e);
					}
				
			}
		});
		try{
//			startService(new Intent(this, ConnectService.class));
				Log.d(LocalData.TAG_SERVICE,"inside try");
				startService(new Intent(MainActivity.this, ConnectService.class));
			}
			catch (Exception e)
			{
				Log.e(LocalData.TAG_SERVICE,""+e);
			}
	}
	void alertmess(String mess) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						return;
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
	void alertfailmess(String mess) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
/*
 * 
 * 
 * 
 * 
 */
	
	private Authen model = null;
	

	public class Loader extends AsyncTask<Void, Void, Authen> {
		@Override
		protected void onPreExecute() {	
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Logging in");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
				
		}

		@Override
		protected Authen doInBackground(Void... arg0) {

			JSONObject jslogin = new JSONObject();
			JSONObject jslogin2 = new JSONObject();
			
			Log.d(Tag2, "Doinbackground");
			try {
				if (LocalData.isConnectsuccess == true) {
					Log.d(Tag2, "Send-1");
					
					try {
						
						jslogin2.put(LocalData.TAG_USERNAME, txtIp.getText().toString());
						jslogin2.put(LocalData.TAG_PASS, txtPort.getText()
								.toString());
						jslogin.put("tag","login");
						jslogin.put("strjson",jslogin2);
						Log.d(Tag2, "Put Json-2");
						Log.i(Tag2, "JsonString: " + jslogin.toString());
					} catch (JSONException e) {						
						Log.e(Tag2, "JSON failed-3" + e);
					}
					ConnectService.mTcpClient.sendMessage(jslogin.toString());
										
					Log.d(Tag2, "JsonString: " + jslogin.toString());						
				}
				else {
					Log.e(Tag2, "Connect not success-4" + LocalData.isConnectsuccess);
				}
			} catch (Exception e) {
				Log.e(Tag2, "Fail parse Json-5" + e);
			}
			long startTime = System.currentTimeMillis();
			try {
				Log.d(Tag2, "Trước while" + LocalData.islogin );				
				while ((System.currentTimeMillis()-startTime)<5000)
	  		{		if (LocalData.islogin == true ) break;
					Log.d("while check", "trong while" + LocalData.islogin );
	  		}
				}
			catch(Exception e)
			{
				Log.e(Tag2,""+e);
			}
			Log.d(Tag2, "end of doinbackground");	
			
			model =  JSonparse.getauthen(LocalData.strreceiver);
				return model;
		}

		@Override
		protected void onPostExecute(final Authen model) {
			Log.i("TESTTROLW", "TESTTROLW: 9");
			super.onPostExecute(model);// sfsmdf
			pDialog.dismiss();
			try {
				Log.d(Tag2,"in postexecute -1 " + LocalData.islogin);
				Log.d(Tag2,"Info " + model.getSuccess() + "---" + model.getTag() + " | "+ model.getUser_group());
				if (LocalData.islogin==true) {
//					if (!model.getSuccess())
//					{
//						alertmess("Đăng nhập thất bại" +model.getSuccess() );
//					}
//					else {
					LocalData.usergroup = model.getUser_group();
					Log.i(LocalData.TAG_LOGIN,"username: "+ model.getUser_name() + "--usergroup: "+ model.getUser_group());
						Log.d(Tag2, "On pregress update - 5");	
						Toast.makeText(MainActivity.this, "Đăng nhập thành công", Toast.LENGTH_SHORT).show();
						Intent inhctr = new Intent(MainActivity.this,MyActivity.class);
						startActivity(inhctr);
						finish();
//					}
				} else {
					alertmess("Đăng nhập thất bại \nVui lòng kiểm tra Tên và Mật khẩu đăng nhập");
					}				
			} catch (Exception e) {
				e.printStackTrace();
				alertmess("Đăng nhập thất bại-3");
				Log.d(Tag2,"in postexecute -2 "+e);
			}
		}
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
